//
//  NetRequestClass.m
//  MyFrameWork
//
//  Created by eason on 16/4/25.
//  Copyright © 2016年 普惠. All rights reserved.
//

#import "NetRequestClass.h"
#import "ApiResponse.h"

@implementation NetRequestClass

+ (BOOL) netWorkReachabilityWithURLString:(NSString *)strUrl
{
    __block BOOL netState = NO;
    NSURL * baseURL = [NSURL URLWithString:strUrl];
    AFHTTPRequestOperationManager * manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
    
    NSOperationQueue * operationQueue = manager.operationQueue;
    
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status){
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [operationQueue setSuspended:NO];
                netState = YES;
                break;
            case AFNetworkReachabilityStatusNotReachable:
                netState = NO;
                break;
                
            default:
                [operationQueue setSuspended:YES];
                break;
        }
    }];
    [manager.reachabilityManager startMonitoring];
    return netState;
}

/***************************************
 在这做判断如果有dic里有errorCode
 调用errorBlock(dic)
 没有errorCode则调用block(dic
 ******************************/

#pragma mark -- GET请求方式
+ (void)NetRequestGetWithRequestURL:(NSString *)requestURLString WithParmeter:(NSDictionary *)parameter WithReturnValueBlock:(ReturnValueBlock)block WithErrorCodeBlock:(ErrorCodeBlock)errorBlock WithFailureBlock:(FailureBlock)failureBlock
{
    AFHTTPRequestOperationManager * manager = [[AFHTTPRequestOperationManager alloc] init];
    AFHTTPRequestOperation * op = [manager GET:requestURLString parameters:parameter success:^(AFHTTPRequestOperation * operation, id responseObject){
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",dic);
        
        ApiResponse * response = [[ApiResponse alloc] initWithAttributes:dic];
        if (response.flag == 0) {//成功
            block(response, dic);
        }else{//失败
            /***************************************
             在这做判断如果有dic里有errorCode
             调用errorBlock(dic)
             没有errorCode则调用block(dic
             ******************************/
            errorBlock(@(response.msgcode), response.msg);
        }
    } failure:^(AFHTTPRequestOperation * operation, NSError * error){
        failureBlock();
    }];
    
    op.responseSerializer = [AFHTTPResponseSerializer serializer];
    [op start];
}

#pragma mark -- POST请求方式
+ (void)NetRequestPOSTWithRequestURL:(NSString *)requestURLString WithParameter:(NSDictionary *)parameter WithReturnValueBlock:(ReturnValueBlock)block WithErrorCodeBlock:(ErrorCodeBlock)errorBlock WithFailureBlock:(FailureBlock)failureBlock
{
    AFHTTPRequestOperationManager * manager = [[AFHTTPRequestOperationManager alloc] init];
    //指定为Json请求格式
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    AFHTTPRequestOperation * op = [manager POST:requestURLString parameters:parameter success:^(AFHTTPRequestOperation * operation , id responseObject){
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        
        
        NSLog(@"%@",operation.request);
        NSLog(@"%@",dic);
        
        ApiResponse * response = [[ApiResponse alloc] initWithAttributes:dic];
        if (response.flag == 0) {//成功
            block(response, dic);
        }else{//失败
            /***************************************
             在这做判断如果有dic里有errorCode
             调用errorBlock(dic)
             没有errorCode则调用block(dic
             ******************************/
            errorBlock(@(response.msgcode), response.msg);
        }
    } failure:^(AFHTTPRequestOperation * operation, NSError * error){
        failureBlock();
    }];
    
    op.responseSerializer = [AFHTTPResponseSerializer serializer];
    [op start];
}

+ (void)NetRequestPOSTWithRequestURL:(NSString *)requestURLString WithParameter:(NSDictionary *)parameter WithImage:(UIImage *)image WithReturnValueBlock:(ReturnValueBlock)block WithErrorCodeBlock:(ErrorCodeBlock)errorBlock WithFailureBlock:(FailureBlock)failureBlock
{
    AFHTTPRequestOperationManager * manager = [[AFHTTPRequestOperationManager alloc] init];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//申明返回的结果是json类型
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    AFHTTPRequestOperation * op =[manager POST:requestURLString parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        NSData *data;
        NSString *fileName;
        NSString * mimeType;
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
            fileName = [NSString stringWithFormat:@"%@.jpeg", str];
            mimeType = @"image/jpeg";
        }
        else
        {
            data = UIImagePNGRepresentation(image);
            fileName = [NSString stringWithFormat:@"%@.png", str];
            mimeType = @"image/png";
        }
        
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:mimeType];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        
        NSLog(@"%@",operation.request);
        NSLog(@"%@",dic);
        
        ApiResponse * response = [[ApiResponse alloc] initWithAttributes:dic];
        if (response.flag == 0) {//成功
            block(response, dic);
        }else{//失败
            /***************************************
             在这做判断如果有dic里有errorCode
             调用errorBlock(dic)
             没有errorCode则调用block(dic
             ******************************/
            errorBlock(@(response.msgcode), response.msg);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failureBlock();
    }];
    
    op.responseSerializer = [AFHTTPResponseSerializer serializer];
    [op start];
}

@end
